﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using System.Web.Mvc;
using WebNext.UI.Models.Comments;
using WebNext.UI.Utils;
using WebNext.Domain;
using WebNext.UI.Properties;
using WebNext.UI.Models.Tags;

namespace WebNext.UI.Models.Entries
{
	public class EntryViewModel : MainViewModel
	{
		public int Id
		{
			get;
			set;
		}

		public string Title
		{
			get;
			private set;
		}

		public int Rank
		{
			get;
			private set;
		}

		public bool IsPublished
		{
			get;
			private set;
		}

		public bool DisplayComments
		{
			get;
			private set;
		}

		public DateTime CreatedOn
		{
			get;
			set;
		}

		public DateTime? LastUpdatedOn
		{
			get;
			set;
		}

		public bool PreviewEdit
		{
			get;
			set;
		}

		public IList<EntryElementViewModel> Elements
		{
			get;
			private set;
		}

		public IList<TagViewModel> Tags
		{
			get;
			private set;
		}

		public CommentsViewModel Comments
		{
			get;
			private set;
		}

		public EntryViewModel(int id, MainViewType viewType, string title, bool isLogged) : base(isLogged)
		{
			this.Id = id;
			this.Title = title;
			this.Elements = new List<EntryElementViewModel>();
			this.Tags = new List<TagViewModel>();

			this.ViewType = viewType;

			if (this.ViewType == MainViewType.Blog)
			{
				this.PageTitle = string.Format(Resources.TitleFormat, RuntimeSettings.SitePrefix, Resources.Blog);
				this.PageName = RuntimeSettings.SitePrefix;
				this.PageDescription = Resources.MyBlog;
			}
			else
			{
				this.PageTitle = string.Format(Resources.TitleFormat, RuntimeSettings.SitePrefix, Resources.Projects);
				this.PageName = Resources.Projects;
				this.PageDescription = Resources.MyProjects;
			}
		}

		public EntryViewModel(Entry entry, bool isLogged) : this(entry.Id, ViewTypeConverter.GetViewTypeByEntryType(entry.Type), entry.Title, isLogged)
		{
			this.Rank = entry.Rank;
			this.IsPublished = entry.IsPublished;
			this.DisplayComments = entry.CommentsEnabled;
			this.CreatedOn = entry.CreatedOn;
			this.LastUpdatedOn = entry.LastUpdatedOn;
			this.Comments = new CommentsViewModel(entry.Comments.OrderBy(c => c.CreatedOn), entry.Id, isLogged);
			this.Elements = entry.Content.Select(c => EntryElementFactory.CreateEntryElementViewModel(c)).OrderBy(c => c.Order).ToList();
			this.Tags = entry.Tags.Select(t => new TagViewModel(t)).ToList();
		}
	}
}